import React, { PureComponent } from 'react'
/**
 * @param {Object} 'r-model' key为需要绑定的state中的变量 value为实际需要绑定的值,例如{msg:this.state.msg}
 * 请尽量保持一致 
 **/
class Input extends PureComponent {
    render() {
        // console.log(this.props)
        if( !(this.props['r-model'] instanceof Object)){
            if(this.props['r-model'] === undefined){
                // let RError = new warn('r-model')
                // console.error(RError)
                console.warn('r-model 未定义')
            }else{
                let RError = new RangeError('r-model 类型错误,请传入一个Object,例如 {key:value}')
                console.error(RError)
            }
            return(
                <span style={{color:'red'}}>
                    请检查r-model传参是否正确,
                    如果不需要传参或者仅仅需要显示一个不需要绑定的值得话,
                    请使用原生input组件
                </span>
            )

        }else{
            let model = this.formatModel()
            let props = Object.assign({},this.props)
            delete props['r-model']
            delete props['this']
            return (
                <input {...props} value={model.value} onChange={e=>this.change(e)}/>
            )
        }
        
    }
    formatModel(){
        let model = this.props['r-model']
        let key = Object.keys(model)[0]
        let value = model[key]
        return {key,value}
    }
    change(e){
        e.persist()
        if(!this.props.this){
            return console.warn('请查看是否传入了调用组件的this')
        }
        const that = this.props.this
        let value
        if(this.props.type === 'number'){
            value = Number(e.target.value)
        }else{
            value = e.target.value
        }
        that.setState({
            [this.formatModel().key]:value
        })
    }
}

export default Input